﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using System.Xml;
using umbraco.cms.helpers;
using umbraco;
using System.Reflection;
using System.Collections.Generic;
using umbraco.interfaces;

namespace DigibizAdvancedMediaPicker
{
    public partial class EditDamp : umbraco.BasePages.UmbracoEnsuredPage
    {
        //This code is copied from the editMedia.aspx page from Umbraco with some small changes.

        public EditDamp()
	    {
            CurrentApp = umbraco.BusinessLogic.DefaultApps.media.ToString();
	    }

        protected umbraco.uicontrols.TabView TabView1;
        protected System.Web.UI.WebControls.TextBox documentName;
        private umbraco.cms.businesslogic.media.Media _media;
        umbraco.controls.ContentControl tmp;

        protected void Page_Load(object sender, System.EventArgs e)
        {
            if (!IsPostBack)
            {
                //This is commented because otherwise the tree would reload if the edit popup is opened.
                //ClientTools.SyncTree(_media.Path, false);
            }
        }

        protected void Save(object sender, System.EventArgs e)
        {
            // error handling test
            if (!Page.IsValid)
            {
                foreach (umbraco.uicontrols.TabPage tp in tmp.GetPanels())
                {
                    tp.ErrorControl.Visible = true;
                    tp.ErrorHeader = umbraco.ui.Text("errorHandling", "errorHeader");
                    tp.CloseCaption = umbraco.ui.Text("close");
                }
            }
            else if (Page.IsPostBack)
            {
                // hide validation summaries
                foreach (umbraco.uicontrols.TabPage tp in tmp.GetPanels())
                {
                    tp.ErrorControl.Visible = false;
                }
            }

            if (umbraco.GlobalSettings.VersionMajor > 4)
            {
                //The value of the properties has been set on IData through IDataEditor in the ContentControl
                //so we need to 'retrieve' that value and set it on the property of the new IContent object.
                //NOTE This is a workaround for the legacy approach to saving values through the DataType instead of the Property 
                //- (The DataType shouldn't be responsible for saving the value - especically directly to the db).
                var member = tmp.GetType().InvokeMember("DataTypes", BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance, null, tmp, null);
                var dataTypes = member as Dictionary<string, IDataType>;

                foreach (var item in dataTypes)
                {
                    _media.getProperty(item.Key).Value = item.Value.Data.Value;
                }
            }

            _media.Save();
            _media.XmlGenerate(new XmlDocument());
            //This is commented because otherwise the tree would reload if the save button is pressed.
            //ClientTools.SyncTree(_media.Path, true);

            //Fill the cache again.
            library.GetMedia(_media.Id, false);

            //Close the popup after the save button is pressed and update the value in the picker.
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "Select", "SetNodeId(" + _media.Id + ");", true);
        }

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);

            _media = new umbraco.cms.businesslogic.media.Media(int.Parse(Request.QueryString["id"]));

            // Save media on first load
            bool exists = SqlHelper.ExecuteScalar<int>("SELECT COUNT(nodeId) FROM cmsContentXml WHERE nodeId = @nodeId",
                                       SqlHelper.CreateParameter("@nodeId", _media.Id)) > 0;
            if (!exists)
                _media.XmlGenerate(new XmlDocument());


            tmp = new umbraco.controls.ContentControl(_media, umbraco.controls.ContentControl.publishModes.NoPublish, "TabView1");
            tmp.Width = Unit.Pixel(666);
            tmp.Height = Unit.Pixel(666);
            plc.Controls.Add(tmp);

            tmp.Save += new System.EventHandler(Save);
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {

        }
        #endregion
    }
}